<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>智能助手</title>
    <style>
        /* 基础样式 */
        :root {
            --primary-color: #2196F3;
            --primary-light: #E3F2FD;
            --primary-dark: #1976D2;
            --success-color: #4CAF50;
            --warning-color: #FFC107;
            --danger-color: #F44336;
            --gray-color: #757575;
            --light-gray: #E0E0E0;
            --white: #ffffff;
            --dark: #212121;
            --shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
            --border-radius: 8px;
            --transition: all 0.3s ease;
        }
        
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'PingFang SC', 'Microsoft YaHei', Arial, sans-serif;
        }
        
        body {
            background: #f7f9fc;
            color: var(--dark);
            line-height: 1.6;
            height: 100vh;
            overflow: hidden;
        }

        /* 布局 */
        .app-container {
            display: flex;
            flex-direction: column;
            height: 100vh;
            max-width: 1440px;
            margin: 0 auto;
            background: var(--white);
            box-shadow: var(--shadow);
        }
        
        .header {
            background: var(--primary-color);
            color: var(--white);
            padding: 16px 24px;
            display: flex;
            align-items: center;
            justify-content: space-between;
        }
        
        .header-title {
            font-size: 20px;
            font-weight: 600;
            display: flex;
            align-items: center;
            gap: 12px;
        }
        
        .main-content {
            display: flex;
            flex: 1;
            overflow: hidden;
        }
        
        /* 侧边栏 */
        .sidebar {
            width: 280px;
            background: #f0f4f8;
            padding: 20px;
            border-right: 1px solid var(--light-gray);
            overflow-y: auto;
            display: flex;
            flex-direction: column;
        }
        
        .sidebar-section {
            margin-bottom: 24px;
        }
        
        .sidebar-title {
            font-size: 16px;
            font-weight: 600;
            margin-bottom: 16px;
            color: var(--primary-dark);
            padding-bottom: 8px;
            border-bottom: 2px solid var(--primary-light);
        }
        
        /* 聊天区域 */
        .chat-container {
            flex: 1;
            display: flex;
            flex-direction: column;
            background: var(--white);
            overflow: hidden;
        }
        
        .chat-toolbar {
            padding: 12px 16px;
            border-bottom: 1px solid var(--light-gray);
            display: flex;
            align-items: center;
            justify-content: space-between;
            background: #fafafa;
        }
        
        .chat-tools {
            display: flex;
            gap: 8px;
        }
        
        .system-info {
            font-size: 13px;
            color: var(--gray-color);
        }
        
        .chat-history {
            flex: 1;
            padding: 20px;
            overflow-y: auto;
        }
        
        .message {
            display: flex;
            margin-bottom: 20px;
            align-items: flex-start;
            animation: fade-in 0.3s ease;
        }
        
        @keyframes fade-in {
            from { opacity: 0; transform: translateY(10px); }
            to { opacity: 1; transform: translateY(0); }
        }
        
        .user-avatar {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            margin-right: 12px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
            flex-shrink: 0;
        }
        
        .message-bubble {
            max-width: 80%;
            padding: 12px 16px;
            border-radius: 18px;
            line-height: 1.5;
            position: relative;
        }
        
        .message.user {
            flex-direction: row-reverse;
        }
        
        .message.user .user-avatar {
            margin-right: 0;
            margin-left: 12px;
        }
        
        .message.user .message-bubble {
            background-color: var(--primary-color);
            color: white;
            border-top-right-radius: 4px;
        }
        
        .message.assistant .message-bubble {
            background-color: #f0f2f5;
            border-top-left-radius: 4px;
        }
        
        .tool-call {
            background-color: #f5f5f5;
            border-left: 3px solid var(--warning-color);
            padding: 8px 12px;
            margin: 8px 0;
            border-radius: 4px;
            font-family: monospace;
            font-size: 14px;
        }
        
        .token-info {
            font-size: 12px;
            color: var(--gray-color);
            margin-top: 8px;
            display: flex;
            gap: 8px;
        }
        
        .chat-input-area {
            padding: 16px;
            border-top: 1px solid var(--light-gray);
            background: #fafafa;
        }
        
        .chat-input-container {
            display: flex;
            background: var(--white);
            border: 1px solid var(--light-gray);
            border-radius: 24px;
            overflow: hidden;
            box-shadow: 0 2px 6px rgba(0,0,0,0.05);
        }
        
        .chat-input {
            flex: 1;
            border: none;
            padding: 12px 16px;
            font-size: 15px;
            outline: none;
        }
        
        .send-btn {
            background: var(--primary-color);
            color: var(--white);
            border: none;
            padding: 0 24px;
            font-weight: 500;
            cursor: pointer;
            transition: var(--transition);
        }
        
        .send-btn:hover {
            background: var(--primary-dark);
        }
        
        /* 表单元素 */
        label {
            display: block;
            margin-bottom: 6px;
            font-size: 14px;
            color: var(--gray-color);
            font-weight: 500;
        }
        
        input, select, textarea {
            width: 100%;
            padding: 10px 12px;
            border: 1px solid var(--light-gray);
            border-radius: var(--border-radius);
            margin-bottom: 16px;
            font-size: 14px;
            transition: border 0.3s;
        }
        
        input:focus, select:focus, textarea:focus {
            border-color: var(--primary-color);
            outline: none;
            box-shadow: 0 0 0 2px rgba(33, 150, 243, 0.1);
        }
        
        textarea {
            min-height: 120px;
            resize: vertical;
        }
        
        .switch {
            position: relative;
            display: inline-block;
            width: 50px;
            height: 24px;
            margin-bottom: 16px;
        }
        
        .switch input {
            opacity: 0;
            width: 0;
            height: 0;
        }
        
        .slider {
            position: absolute;
            cursor: pointer;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background-color: #ccc;
            transition: .3s;
            border-radius: 24px;
        }
        
        .slider:before {
            position: absolute;
            content: "";
            height: 16px;
            width: 16px;
            left: 4px;
            bottom: 4px;
            background-color: white;
            transition: .3s;
            border-radius: 50%;
        }
        
        input:checked + .slider {
            background-color: var(--primary-color);
        }
        
        input:checked + .slider:before {
            transform: translateX(26px);
        }
        
        select {
            appearance: none;
            background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='16' height='16' viewBox='0 0 24 24' fill='none' stroke='%23757575' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='M6 9l6 6 6-6'/%3E%3C/svg%3E");
            background-repeat: no-repeat;
            background-position: right 12px center;
            padding-right: 32px;
        }
        
        /* 按钮 */
        .btn {
            display: inline-flex;
            align-items: center;
            justify-content: center;
            padding: 8px 16px;
            border: none;
            border-radius: var(--border-radius);
            font-size: 14px;
            font-weight: 500;
            cursor: pointer;
            transition: var(--transition);
            background: var(--white);
            color: var(--dark);
            border: 1px solid var(--light-gray);
        }
        
        .btn:hover {
            background: #f5f5f5;
        }
        
        .btn-primary {
            background: var(--primary-color);
            color: var(--white);
            border: none;
        }
        
        .btn-primary:hover {
            background: var(--primary-dark);
        }
        
        .btn-group {
            display: flex;
            gap: 8px;
        }
        
        /* 历史记录列表 */
        .history-list {
            border: 1px solid var(--light-gray);
            border-radius: var(--border-radius);
            overflow: hidden;
            margin-bottom: 16px;
            max-height: 200px;
            overflow-y: auto;
        }
        
        .history-item {
            padding: 10px 16px;
            border-bottom: 1px solid var(--light-gray);
            cursor: pointer;
            transition: var(--transition);
        }
        
        .history-item:hover {
            background: var(--primary-light);
        }
        
        .history-item:last-child {
            border-bottom: none;
        }
        
        /* 加载指示器 */
        .loading {
            display: inline-block;
            width: 20px;
            height: 20px;
            border: 2px solid rgba(33, 150, 243, 0.3);
            border-radius: 50%;
            border-top-color: var(--primary-color);
            animation: spin 1s ease-in-out infinite;
        }
        
        @keyframes spin {
            to { transform: rotate(360deg); }
        }
        
        /* 响应式设计 */
        @media (max-width: 768px) {
            .main-content {
                flex-direction: column;
            }
            
            .sidebar {
                width: 100%;
                height: auto;
                max-height: 300px;
                border-right: none;
                border-bottom: 1px solid var(--light-gray);
            }
        }
        
        /* 标签页切换 */
        .tab-container {
            margin-bottom: 16px;
        }
        
        .tab-nav {
            display: flex;
            border-bottom: 1px solid var(--light-gray);
            margin-bottom: 16px;
        }
        
        .tab-btn {
            padding: 8px 16px;
            background: none;
            border: none;
            border-bottom: 2px solid transparent;
            cursor: pointer;
            font-weight: 500;
            transition: var(--transition);
            color: var(--gray-color);
        }
        
        .tab-btn.active {
            border-bottom-color: var(--primary-color);
            color: var(--primary-color);
        }
        
        .tab-content {
            display: none;
        }
        
        .tab-content.active {
            display: block;
        }
    </style>
</head>
<body>
    <div class="app-container">
        <header class="header">
            <div class="header-title">
                <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                    <circle cx="12" cy="12" r="10"></circle>
                    <path d="M8.56 15.15c-.7-.63-.95-1.72-.95-3.15 0-1.43.25-2.5.95-3.15a1.95 1.95 0 0 1 1.55-.75 1.99 1.99 0 0 1 1.55.75c.7.63.95 1.71.95 3.15 0 1.43-.25 2.51-.95 3.15a1.97 1.97 0 0 1-1.55.74 1.93 1.93 0 0 1-1.55-.74z"></path>
                    <path d="M13.45 12.4H15.5c.55 0 1 0 1.4.09.37.07.7.21.96.46.26.26.4.58.48.95.08.37.08.77 08 1.09v.08c0 .33 0 .72-.08 1.09a2.02 2.02 0 0 1-.48.95c-.27.26-.6.4-.96.47-.4.08-.85.09-1.4.09h-2.05V8.13h-1.78"></path>
                </svg>
                智能助手
            </div>
        </header>
        
        <div class="main-content">
            <!-- 侧边栏配置区 -->
            <aside class="sidebar">
                <!-- 系统提示词配置 -->
                <div class="sidebar-section">
                    <h3 class="sidebar-title">系统提示词</h3>
                    <textarea id="system-prompt" placeholder="请输入系统提示词，定义AI助手的行为和角色"></textarea>
                    <div class="btn-group">
                        <button class="btn btn-primary" id="apply-prompt-btn">应用</button>
                    </div>
                </div>
                
                <!-- Simplified model selection part -->
                <div class="sidebar-section">
                    <h3 class="sidebar-title">模型配置</h3>
                    
                    <div>
                        <label for="provider-select">选择提供商</label>
                        <select id="provider-select">
                            <option value="deepseek">DeepSeek</option>
                            <option value="qwen">千问</option>
                        </select>
                    </div>
                    
                    <div id="api-key-section">
                        <label for="api-key-input">API密钥</label>
                        <input id="api-key-input" type="password" placeholder="输入API密钥">
                    </div>
                    
                    <div>
                        <label for="model-select">选择模型</label>
                        <select id="model-select">
                            <!-- 将根据提供商动态填充 -->
                        </select>
                    </div>
                    
                    <div>
                        <label for="toggle-tools">启用工具支持</label>
                        <label class="switch">
                            <input type="checkbox" id="toggle-tools">
                            <span class="slider"></span>
                        </label>
                        <div id="tools-info" style="font-size: 12px; color: #888; margin-top: -10px;">
                            启用后可以让AI调用外部工具
                        </div>
                    </div>
                    
                    <div class="btn-group">
                        <button class="btn btn-primary" id="save-config-btn">保存配置</button>
                    </div>
                </div>
                
                <!-- 历史对话管理 -->
                <div class="sidebar-section">
                    <h3 class="sidebar-title">历史对话</h3>
                    <div class="btn-group" style="margin-bottom: 12px;">
                        <button class="btn" id="load-history-btn">加载历史</button>
                        <button class="btn" id="save-chat-btn">保存对话</button>
                    </div>
                    <div class="history-list" id="history-list" style="display: none;">
                        <!-- 历史对话项将动态添加 -->
                    </div>
                </div>
            </aside>
            
            <!-- 聊天区域 -->
            <div class="chat-container">
                <!-- 聊天工具栏 -->
                <div class="chat-toolbar">
                    <div class="chat-tools">
                        <button class="btn btn-primary" id="new-chat-btn">新对话</button>
                        <button class="btn" id="clear-chat-btn">清空对话</button>
                    </div>
                    <div class="system-info">
                        <div>系统提示词: <span id="current-system-prompt">未设置</span></div>
                        <div>当前模型: <span id="current-model-info">未选择</span></div>
                        <div>工具支持: <span id="tools-status">未启用</span></div>
                    </div>
                </div>
                
                <!-- 聊天历史 -->
                <div class="chat-history" id="chat-history">
                    <!-- 消息将动态添加 -->
                </div>
                
                <!-- 聊天输入区域 -->
                <div class="chat-input-area">
                    <div class="chat-input-container">
                        <input type="text" class="chat-input" id="chat-input" placeholder="输入消息，按回车发送">
                        <button class="send-btn" id="send-btn">发送</button>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script>
        // DOM元素
        const chatHistoryEl = document.getElementById('chat-history');
        const chatInputEl = document.getElementById('chat-input');
        const sendBtn = document.getElementById('send-btn');
        const systemPromptEl = document.getElementById('system-prompt');
        const currentSystemPromptEl = document.getElementById('current-system-prompt');
        const currentModelInfoEl = document.getElementById('current-model-info');
        const toolsStatusEl = document.getElementById('tools-status');
        const applyPromptBtn = document.getElementById('apply-prompt-btn');
        const newChatBtn = document.getElementById('new-chat-btn');
        const clearChatBtn = document.getElementById('clear-chat-btn');
        const loadHistoryBtn = document.getElementById('load-history-btn');
        const saveChatBtn = document.getElementById('save-chat-btn');
        const historyListEl = document.getElementById('history-list');
        const providerSelectEl = document.getElementById('provider-select');
        const modelSelectEl = document.getElementById('model-select');
        const apiKeyInputEl = document.getElementById('api-key-input');
        const toggleToolsEl = document.getElementById('toggle-tools');
        const saveConfigBtn = document.getElementById('save-config-btn');

        // 标签页切换
        const tabBtns = document.querySelectorAll('.tab-btn');
        const tabContents = document.querySelectorAll('.tab-content');
        
        // 存储模型列表
        let availableModels = [];
        
        // 初始化标签页切换
        tabBtns.forEach(btn => {
            btn.addEventListener('click', function() {
                // 移除所有活动标签
                tabBtns.forEach(b => b.classList.remove('active'));
                tabContents.forEach(c => c.classList.remove('active'));
                
                // 设置当前活动标签
                const tabId = this.getAttribute('data-tab');
                this.classList.add('active');
                document.getElementById(tabId).classList.add('active');
            });
        });
        
        // 监听提供商选择变化，更新模型选项和密钥占位符
        providerSelectEl.addEventListener('change', function() {
            const provider = this.value;
            updateModelOptions(provider);
            
            // 更新 API 密钥输入框的占位符
            if (provider === 'deepseek') {
                apiKeyInputEl.placeholder = "输入DeepSeek API密钥";
            } else if (provider === 'qwen') {
                apiKeyInputEl.placeholder = "输入千问 API密钥";
            }
        });

        // 更新模型选项函数
        function updateModelOptions(provider) {
            // 清空当前选项
            modelSelectEl.innerHTML = '';
            
            if (provider === 'deepseek') {
                const deepseekModels = [
                    {name: 'deepseek-chat', description: '基础对话模型'},
                    {name: 'deepseek-reasoner', description: '推理增强模型'}
                ];
                
                deepseekModels.forEach(model => {
                    const option = document.createElement('option');
                    option.value = model.name;
                    option.textContent = `${model.name} - ${model.description}`;
                    modelSelectEl.appendChild(option);
                });
            } else if (provider === 'qwen') {
                const option = document.createElement('option');
                option.value = 'qwen3-235b-a22b';
                option.textContent = 'qwen3-235b-a22b - 通义千问大语言模型';
                modelSelectEl.appendChild(option);
            }
        }
        
        // 工具开关状态变化
        toggleToolsEl.addEventListener('change', function() {
            const enabled = this.checked;
            toolsStatusEl.textContent = enabled ? '已启用' : '未启用';
            toolsStatusEl.style.color = enabled ? '#4CAF50' : '#F44336';
            
            // 调用后端切换工具状态
            window.pywebview.api.toggle_tools(enabled).then(data => {
                if (!data.success) {
                    alert(`工具状态切换失败: ${data.error_message}`);
                    this.checked = !enabled; // 恢复开关状态
                }
            });
        });

        // 初始化页面
        window.addEventListener('pywebviewready', function() {
            // 获取配置
            window.pywebview.api.get_config().then(data => {
                if (data.success) {
                    // 设置当前提供商
                    if (data.current_provider) {
                        providerSelectEl.value = data.current_provider;
                        
                        // 设置对应的API密钥
                        if (data.current_provider === 'deepseek') {
                            apiKeyInputEl.value = data.api_keys.deepseek || '';
                            apiKeyInputEl.placeholder = "输入DeepSeek API密钥";
                        } else if (data.current_provider === 'qwen') {
                            apiKeyInputEl.value = data.api_keys.qwen || '';
                            apiKeyInputEl.placeholder = "输入千问 API密钥";
                        }
                        
                        // 更新模型选项
                        updateModelOptions(data.current_provider);
                    } else {
                        // 默认选择DeepSeek
                        updateModelOptions('deepseek');
                    }
                    
                    // 设置当前模型
                    if (data.current_model) {
                        // 确保模型选项加载后再设置
                        setTimeout(() => {
                            modelSelectEl.value = data.current_model;
                            currentModelInfoEl.textContent = `${data.current_provider || 'DeepSeek'} / ${data.current_model}`;
                        }, 100);
                    }
                    
                    // 设置工具状态
                    toggleToolsEl.checked = data.use_tools;
                    toolsStatusEl.textContent = data.use_tools ? '已启用' : '未启用';
                    toolsStatusEl.style.color = data.use_tools ? '#4CAF50' : '#F44336';
                    
                    // 设置系统提示词
                    if (data.system_message) {
                        systemPromptEl.value = data.system_message;
                        currentSystemPromptEl.textContent = truncateText(data.system_message, 40);
                    }
                }
            });
        });
        
        // 发送消息
        sendBtn.addEventListener('click', function() {
            sendUserMessage();
        });
        
        // 回车发送消息
        chatInputEl.addEventListener('keydown', function(e) {
            if (e.key === 'Enter' && !e.shiftKey) {
                e.preventDefault();
                sendUserMessage();
            }
        });
        
        // 应用系统提示词
        applyPromptBtn.addEventListener('click', function() {
            const prompt = systemPromptEl.value.trim();
            if (!prompt) return;
            
            window.pywebview.api.set_system_prompt(prompt).then(data => {
                if (data.success) {
                    currentSystemPromptEl.textContent = truncateText(prompt, 40);
                    chatHistoryEl.innerHTML = '';
                }
            });
        });
        
        // 新对话
        newChatBtn.addEventListener('click', function() {
            window.pywebview.api.clear_chat().then(data => {
                if (data.success) {
                    chatHistoryEl.innerHTML = '';
                    historyListEl.style.display = 'none';
                }
            });
        });
        
        // 清空对话
        clearChatBtn.addEventListener('click', function() {
            window.pywebview.api.clear_chat().then(data => {
                if (data.success) {
                    chatHistoryEl.innerHTML = '';
                }
            });
        });
        
        // 加载历史对话
        loadHistoryBtn.addEventListener('click', function() {
            window.pywebview.api.get_conversation_list().then(data => {
                if (data.success) {
                    historyListEl.innerHTML = '';
                    
                    if (data.conversations.length === 0) {
                        const emptyEl = document.createElement('div');
                        emptyEl.className = 'history-item';
                        emptyEl.textContent = '没有历史对话';
                        historyListEl.appendChild(emptyEl);
                    } else {
                        data.conversations.forEach(fileName => {
                            const itemEl = document.createElement('div');
                            itemEl.className = 'history-item';
                            itemEl.textContent = fileName;
                            itemEl.addEventListener('click', function() {
                                loadConversation(fileName);
                            });
                            historyListEl.appendChild(itemEl);
                        });
                    }
                    
                    historyListEl.style.display = historyListEl.style.display === 'none' ? 'block' : 'none';
                }
            });
        });
        
        // 保存对话
        saveChatBtn.addEventListener('click', function() {
            const fileName = prompt('请输入保存文件名:', '对话_' + new Date().toISOString().slice(0, 10));
            if (!fileName) return;
            
            const finalName = fileName.endsWith('.json') ? fileName : fileName + '.json';
            window.pywebview.api.save_conversation(finalName).then(data => {
                if (data.success) {
                    alert('对话保存成功!');
                } else {
                    alert('保存失败: ' + (data.error_message || '未知错误'));
                }
            });
        });
        
        // 修改保存配置部分的JavaScript代码
        saveConfigBtn.addEventListener('click', function() {
            // 获取当前选中的提供商
            const provider = providerSelectEl.value;
            
            // 获取API密钥
            const apiKey = apiKeyInputEl.value.trim();
            
            const model = modelSelectEl.value;
            const useTools = toggleToolsEl.checked;
            
            if (!apiKey) {
                alert('请输入API密钥');
                return;
            }
            
            window.pywebview.api.save_config(provider, apiKey, model, useTools).then(data => {
                if (data.success) {
                    alert('配置保存成功!');
                    currentModelInfoEl.textContent = `${provider} / ${model}`;
                } else {
                    alert('保存失败: ' + (data.error_message || '未知错误'));
                }
            });
        });
        
        // 发送用户消息
        function sendUserMessage() {
            const message = chatInputEl.value.trim();
            if (!message) return;
            
            // 清空输入框
            chatInputEl.value = '';
            
            // 添加用户消息到界面
            appendMessage('user', message);
            
            // 添加加载中的消息
            const loadingMessage = appendLoadingMessage();
            
            // 调用后端API发送消息
            window.pywebview.api.send_message(message).then(response => {
                if (response.success) {
                    if (response.processing) {
                        // 启动轮询获取结果
                        pollForResponse(loadingMessage);
                    } else {
                        // 直接处理响应
                        loadingMessage.remove();
                        appendMessage('assistant', response.content, response);
                    }
                } else {
                    // 显示错误消息
                    loadingMessage.remove();
                    appendMessage('assistant', `出错: ${response.error_message || '未知错误'}`);
                }
            }).catch(error => {
                // 移除加载状态
                loadingMessage.remove();
                appendMessage('assistant', '发送消息时出错，请检查连接');
            });
        }
        
        // 轮询获取响应结果
        function pollForResponse(loadingMessage, attemptCount = 0, maxAttempts = 30) {
            if (attemptCount >= maxAttempts) {
                loadingMessage.remove();
                appendMessage('assistant', '请求超时，请重试');
                return;
            }
            
            // 调用后端API轮询获取结果
            // 优化轮询策略：前10次快速轮询，之后逐渐增加时间间隔
            const interval = attemptCount < 10 ? 500 : Math.min(2000, 500 + attemptCount * 100);
            
            setTimeout(() => {
                window.pywebview.api.get_response_chunk().then(response => {
                    if (response && response.success) {
                        if (response.completed) {
                            // 响应已完成，移除加载消息，添加响应
                            loadingMessage.remove();
                            appendMessage('assistant', response.content, response);
                        } else if (response.processing) {
                            // 添加轮询指示器，让用户知道系统仍在工作
                            if (attemptCount % 5 === 0) {
                                const bubble = loadingMessage.querySelector('.message-bubble');
                                if (bubble && bubble.querySelector('.loading')) {
                                    bubble.textContent = `正在处理请求... (${attemptCount+1}s)`;
                                    const loadingEl = document.createElement('div');
                                    loadingEl.className = 'loading';
                                    bubble.appendChild(loadingEl);
                                }
                            }
                            // 响应处理中，继续轮询
                            pollForResponse(loadingMessage, attemptCount + 1, maxAttempts);
                        } else if (response.content) {
                            // 有内容但未完成（用于真正的流式输出）
                            updateLoadingMessage(loadingMessage, response.content);
                            pollForResponse(loadingMessage, attemptCount + 1, maxAttempts);
                        }
                    } else {
                        // 错误处理
                        loadingMessage.remove();
                        appendMessage('assistant', `出错: ${response.error_message || '未知错误'}`);
                    }
                }).catch((error) => {
                    // 出错，停止轮询
                    loadingMessage.remove();
                    appendMessage('assistant', '获取响应时出错，请重试');
                    console.error('轮询错误:', error);
                });
            }, interval);
        }
        
        // 更新加载消息的内容（用于流式输出）
        function updateLoadingMessage(loadingMessage, content) {
            // 获取消息气泡元素
            const bubble = loadingMessage.querySelector('.message-bubble');
            if (bubble) {
                // 移除加载动画
                const loadingEl = bubble.querySelector('.loading');
                if (loadingEl) {
                    loadingEl.remove();
                }
                // 更新内容
                bubble.textContent = content;
            }
        }
        
        // 加载对话
        function loadConversation(fileName) {
            window.pywebview.api.load_conversation(fileName).then(data => {
                if (data.success) {
                    // 清空当前聊天记录
                    chatHistoryEl.innerHTML = '';
                    
                    // 更新系统提示词
                    const systemMsg = data.messages.find(msg => msg.role === 'system');
                    if (systemMsg) {
                        currentSystemPromptEl.textContent = truncateText(systemMsg.content, 40);
                        systemPromptEl.value = systemMsg.content;
                    }
                    
                    // 添加所有消息到UI
                    data.messages.forEach(msg => {
                        if (msg.role !== 'system') {
                            appendMessage(msg.role, msg.content);
                        }
                    });
                    
                    // 隐藏历史列表
                    historyListEl.style.display = 'none';
                }
            });
        }
        
        // 添加消息到聊天界面
        function appendMessage(role, content, responseData = null) {
            const messageDiv = document.createElement('div');
            messageDiv.className = `message ${role}`;
            
            const avatar = document.createElement('img');
            avatar.className = 'user-avatar';
            avatar.src = role === 'user' 
                ? ''
                : '';
            
            const bubble = document.createElement('div');
            bubble.className = 'message-bubble';
            bubble.textContent = content;
            
            messageDiv.appendChild(avatar);
            messageDiv.appendChild(bubble);
            
            // 如果是助手回复且有工具调用，添加工具调用信息
            if (role === 'assistant' && responseData && responseData.tool_calls && responseData.tool_calls.length > 0) {
                const toolCallsDiv = document.createElement('div');
                toolCallsDiv.className = 'tool-calls';
                
                responseData.tool_calls.forEach(toolCall => {
                    const toolCallDiv = document.createElement('div');
                    toolCallDiv.className = 'tool-call';
                    toolCallDiv.textContent = `工具: ${toolCall.name} - ${toolCall.result || '无结果'}`;
                    toolCallsDiv.appendChild(toolCallDiv);
                });
                
                bubble.appendChild(toolCallsDiv);
            }
            
            // 如果有token信息，添加token计数
            if (role === 'assistant' && responseData) {
                let hasTokenInfo = false;
                const tokenInfoDiv = document.createElement('div');
                tokenInfoDiv.className = 'token-info';
                
                if (responseData.prompt_tokens) {
                    const promptTokensSpan = document.createElement('span');
                    promptTokensSpan.textContent = `输入: ${responseData.prompt_tokens}`;
                    tokenInfoDiv.appendChild(promptTokensSpan);
                    hasTokenInfo = true;
                }
                
                if (responseData.completion_tokens) {
                    const completionTokensSpan = document.createElement('span');
                    completionTokensSpan.textContent = `输出: ${responseData.completion_tokens}`;
                    tokenInfoDiv.appendChild(completionTokensSpan);
                    hasTokenInfo = true;
                }
                
                if (responseData.total_prompt_tokens) {
                    const totalPromptTokensSpan = document.createElement('span');
                    totalPromptTokensSpan.textContent = `总输入: ${responseData.total_prompt_tokens}`;
                    tokenInfoDiv.appendChild(totalPromptTokensSpan);
                    hasTokenInfo = true;
                }
                
                if (responseData.total_completion_tokens) {
                    const totalCompletionTokensSpan = document.createElement('span');
                    totalCompletionTokensSpan.textContent = `总输出: ${responseData.total_completion_tokens}`;
                    tokenInfoDiv.appendChild(totalCompletionTokensSpan);
                    hasTokenInfo = true;
                }
                
                if (responseData.api_call_count && responseData.api_call_count > 1) {
                    const apiCallCountSpan = document.createElement('span');
                    apiCallCountSpan.textContent = `API调用: ${responseData.api_call_count}次`;
                    tokenInfoDiv.appendChild(apiCallCountSpan);
                    hasTokenInfo = true;
                }
                
                if (hasTokenInfo) {
                    bubble.appendChild(tokenInfoDiv);
                }
            }
            
            chatHistoryEl.appendChild(messageDiv);
            
            // 滚动到底部
            chatHistoryEl.scrollTop = chatHistoryEl.scrollHeight;
            
            return messageDiv;
        }
        
        // 添加加载中的消息
        function appendLoadingMessage() {
            const messageDiv = document.createElement('div');
            messageDiv.className = 'message assistant loading-message';
            
            const avatar = document.createElement('img');
            avatar.className = 'user-avatar';
            avatar.src = '';
            
            const bubble = document.createElement('div');
            bubble.className = 'message-bubble';
            
            const loadingEl = document.createElement('div');
            loadingEl.className = 'loading';
            bubble.appendChild(loadingEl);
            
            messageDiv.appendChild(avatar);
            messageDiv.appendChild(bubble);
            
            chatHistoryEl.appendChild(messageDiv);
            
            // 滚动到底部
            chatHistoryEl.scrollTop = chatHistoryEl.scrollHeight;
            
            return messageDiv;
        }
        
        // 文本截断函数
        function truncateText(text, maxLength) {
            if (!text) return '';
            return text.length > maxLength ? text.substring(0, maxLength) + '...' : text;
        }
    </script>
</body>
</html>